package com.example.test.多线程;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 晓果冻
 * @version 1.0
 * @date 2022/5/29 9:39
 */
public class Thread01 {
    class Res {
        private String name;
        private char sex;
        private boolean flag = false;

        @Override
        public String toString() {
            return "Res{" +
                    "name='" + name + '\'' +
                    ", sex=" + sex +
                    '}';
        }
    }

    class InputThread implements Runnable {
        private Res res;

        public InputThread(Res res) {
            this.res = res;
        }

        @Override
        public void run() {
            int count = 0;
            while (true) {
                synchronized (res) {
                    if(res.flag){
                        try {
                            res.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (count == 0) {
                        res.name = "晓果冻";
                        res.sex = '男';
                    } else {
                        res.name = "MC栋栋";
                        res.sex = '女';
                    }
                    count = (count + 1) % 2;
                    res.flag = true;
                    res.notify();
                }
            }
        }
    }

    class OutoutThread extends Thread {
        private Res res;
        public OutoutThread(Res res) {
            this.res = res;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (res) {
                    if (!res.flag) {
                        try {
                            res.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(res.toString());
                    res.flag = false;
                    res.notify();
                }

            }
        }
    }

    public static void main(String[] args) {
        new Thread01().print();
    }

    public void print() {
        Res res = new Res();
        InputThread inputThread = new InputThread(res);
        OutoutThread outoutThread = new OutoutThread(res);
        new Thread(inputThread).start();
        outoutThread.start();
    }
}
